package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	cases_proto "ticket-system/cases/pb"
	database "ticket-system/db"
	ticket_proto "ticket-system/ticket/pb"
)

func main() {
	// 创建数据库
	database.OperateTables{}.CreateTable()
	// 连接案件服务
	casesClient, casesConn := getCasesClient()
	// 连接工单服务
	ticketsClient, ticketsConn := getTicketsClient()

	// 测试案件接口
	defer casesConn.Close()
	if casesClient != nil {
		fmt.Println("客户端发起远程调用-cases")
		// SayHi
		res, _ := casesClient.SayHi(context.Background(), &cases_proto.Req{Message: "我从客户端来"})
		fmt.Println("SayHello API：" + res.GetMessage())
		// GetCases
		casesRes, _ := casesClient.GetCases(context.Background(), &cases_proto.GetCaseReq{UserId: "1001"})
		fmt.Println("GetCases API：", casesRes.Cases)
		// CreateCases
		createCasesRes, _ := casesClient.CreateCases(context.Background(), &cases_proto.CreateCaseReq{UserId: "1001"})
		fmt.Println("CreateCases API：", createCasesRes.IsSuccess)
	}

	// 测试工单接口
	defer ticketsConn.Close()
	if ticketsClient != nil {
		fmt.Println("客户端发起远程调用-tickets")
		// SayHi
		req, _ := ticketsClient.SayHi(context.Background(), &ticket_proto.Req{Message: "我从客户端来"})
		fmt.Println("SayHello API：", req.GetMessage())
		// UpdateDataAndDoc
		req2, _ := ticketsClient.UpdateDataAndDoc(context.Background(), &ticket_proto.DataAndDocReq{CaseId: 1, Type: 1})
		fmt.Println("UpdateDataAndDoc API：", req2.GetIsSuccess())
		// FinishDataAndDoc
		req3, _ := ticketsClient.FinishDataAndDoc(context.Background(), &ticket_proto.FinishDataAndDocReq{TicketId: 1, Type: 1})
		fmt.Println("FinishDataAndDoc API：", req3.GetIsSuccess())
		// GetAllTicket
		req4, _ := ticketsClient.GetAllTicket(context.Background(), &ticket_proto.DataAndDocReq{CaseId: 1})
		fmt.Println("GetAllTicket API：", req4.GetItems())
	}
}

func getTicketsClient() (ticket_proto.TicketGRPCClient, *grpc.ClientConn) {
	conn, e := grpc.Dial("localhost:8889", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if e != nil {
		return nil, nil
	}

	client := ticket_proto.NewTicketGRPCClient(conn)
	return client, conn
}

func getCasesClient() (cases_proto.CasesGRPCClient, *grpc.ClientConn) {
	conn, e := grpc.Dial("localhost:8888", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if e != nil {
		return nil, nil
	}

	client := cases_proto.NewCasesGRPCClient(conn)
	return client, conn
}
